#自定义用户认证的后端，实现既能用户名登录又能手机号登录
import re
from django.contrib.auth.backends import ModelBackend
from users.models import User
from itsdangerous import BadData, URLSafeTimedSerializer
from django.conf import settings

def GetUserByUsernameOrPassWord(account):
    try:
        if re.match(r'^1[3-9]\d{9}$',account):
                #手机号
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user

class UserNameMobileBack(ModelBackend):
    #重写用户认证方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = GetUserByUsernameOrPassWord(username)
        if user and user.check_password(password):
            return user
        else:
            return None
        
#生成郵箱激活連接 
def generate_verify_email_url(user):
    #生成一個token令牌
    serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
    data = {
        'user_id': user.id,
        'email': user.email
    }
    token = serializer.dumps(data)
    return settings.EMAIL_VERIFY_URL + '?token=' + token

#解除token，返回user对象
def check_verify_email_token(token):
    serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        #从data中取出user_id email
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return None
        else:
            return user